package com.centriole.service.workflow.controller;

import com.centriole.common.feignApi.PaasUserFeignClient;
import com.centriole.service.workflow.common.QueryVo;
import com.centriole.service.workflow.entity.InstanceHistory;
import com.centriole.service.workflow.entity.ProInstance;
import com.centriole.service.workflow.entity.TaskModel;
import com.centriole.service.workflow.enums.CancelTask;
import com.centriole.service.workflow.service.ProcessService;
import com.centriole.service.workflow.service.impl.FlowTraceService;
import com.centriole.service.workflow.service.vo.CompleteTaskRequest;
import com.centriole.service.workflow.util.AjaxResult;
import com.centriole.service.workflow.util.ResultJson;
import com.centriole.service.workflow.util.UserUtils;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/flow/task")
public class FlowController {
    @Resource
    private ProcessService processService;
    @Resource
    private FlowTraceService flowTraceService;
    @Resource
    PaasUserFeignClient paasUserFeignClient;

    @RequestMapping(value = "/toStartFlow")
    public String startFlow(Model model){
        model.addAttribute("process", JSONArray.fromObject(processService.getDeployedProcess()));
        model.addAttribute("apps",JSONArray.fromObject( paasUserFeignClient.listAllApps() ));
        return "flowpages/startFlow";
    }

    /**
     * 检查查询对象，并返回SpringMVC的模型Model
     * @param model
     * @param query
     * @return
     */
    private Model checkQueryVoAndAddModel(Model model , QueryVo query){
        model.addAttribute("process", JSONArray.fromObject(processService.select("")));
        if(StringUtils.isNoneBlank( query.getUserId() )){
            model.addAttribute("userId", query.getUserId());
        }
        if(StringUtils.isNoneBlank( query.getUserId() )){
            model.addAttribute("executorName", query.getExecutorName());
        }
        if(StringUtils.isNotBlank( query.getAppName() )){
            model.addAttribute("appName",query.getAppName() );
        }
        return model;
    }

    /**
     * 页面跳转 待办任务
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = "/toTaskList")
    public String toTaskList(Model model ,QueryVo query){
        model.addAttribute("process", JSONArray.fromObject(processService.select("")));
        model = checkQueryVoAndAddModel(model,query);
        return "flowpages/taskList";
    }

    /**
     * 页面跳转 我的流程(已办理)
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = "/toTaskMyHistory")
    public String toTaskMyHistory(Model model, HttpServletRequest request ,  QueryVo query){
        model.addAttribute("instanceId", request.getParameter("instanceId"));
        model = checkQueryVoAndAddModel(model,query);
        return "flowpages/taskMyHistoryProcessList";
    }

    /**
     * 页面跳转 我的流程(办理中)
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = "/toTaskMyProcess")
    public String toTaskMyProcess(Model model , QueryVo query){
        model = checkQueryVoAndAddModel(model,query);
        return "flowpages/taskMyProcessList";
    }

    /**
     * 页面跳转 已办列表
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = "/toTaskDealList")
    public String toTaskDealList(Model model , QueryVo query){
        model = checkQueryVoAndAddModel(model,query);
        return "flowpages/taskDealList";
    }

    /**
     * 流程办理历史
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/toTaskDealHistoryList")
    public String toTaskDealHistoryList(Model model , HttpServletRequest request){
        String instanceId = request.getParameter("instanceId");
        model.addAttribute("instanceId", instanceId);
        return "flowpages/taskDealHistoryList";
    }

    /**
     *  页面跳转(或者弹窗)  到普通任务执行页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/toComplete")
    public ModelAndView toComplete(ModelAndView model , HttpServletRequest request){
        String taskId = request.getParameter("taskId");
        //审批人id
        String approverId = request.getParameter("approverId");
        String executorName = request.getParameter("executorName");
        if(StringUtils.isNotBlank(approverId)) model.addObject("approverId",approverId);
        if( executorName!= null  ) model.addObject("executorName", StringUtils.isBlank(executorName)? UserUtils.currentUserInfo().getName():executorName);
        model.setViewName("flowpages/taskComplete");
        model.addObject("beforTaskModel", JSONObject.fromObject(processService.getBeforTaskByTaskId(taskId)));
        TaskModel tm = processService.getTaskByTaskId(taskId);
        tm.setTaskType(request.getParameter("taskType"));
        model.addObject("taskModel", JSONObject.fromObject(tm));
        return model;
    }

    /**
     * 发起流程
     * @param proInstance
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public AjaxResult start(ProInstance proInstance , HttpServletRequest request){
    	System.out.println(proInstance);
    	String userId = proInstance.getCreatorId()==null?"defalut":proInstance.getCreatorId();
    	proInstance.setCreatorId(userId);
    	proInstance.setModifierId(userId);
    	
    	if (proInstance.getProcessId().equals("")) {
    		return AjaxResult.Error();
		}
        try {
            processService.start(proInstance, request);
            return AjaxResult.Success("保存成功", proInstance);
        } catch (Exception e) {
            return AjaxResult.Error(e.getMessage());
        }
    }

    /**
     * 挂起流程实例
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/suspendInstance")
    public Object suspendInstance(HttpServletRequest request) {
        try {
            processService.suspendInstance(request.getParameter("instanceId"));
            return AjaxResult.Success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.Error(e.getMessage());
        }
    }

    /**
     * 激活被挂起的流程实例
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/activateInstance")
    public Object activateInstance(HttpServletRequest request) {
        try {
            processService.activateInstance(request.getParameter("instanceId"));
            return AjaxResult.Success();
        } catch (Exception e) {
            return AjaxResult.Error(e.getMessage());
        }
    }

    /**
     * 获取任务列表
     * @param appName
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTask", method = RequestMethod.POST)
    public Object getTask( String appName , String userId ){
        List<TaskModel> list = processService.getTask(appName,userId);
        return ResultJson.usePageInfo(new PageInfo<>(list));
    }

    /**
     * 获取 我的流程 ,根据 'sFinished' 字段值来 具体查询 已办理 还是 办理中
     * @param request
     * @param queryVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyProcess", method = RequestMethod.POST)
    public Object getMyProcess(HttpServletRequest request,QueryVo queryVo){
        String isFinished = request.getParameter("isFinished");
        List<TaskModel> list = processService.getMyProcess(isFinished,queryVo);
        return ResultJson.usePageInfo(new PageInfo<>(list));
    }

    /**
     * 获取 待办列表
     * @param request
     * @param queryVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDeal", method = RequestMethod.POST)
    public Object getDeal(HttpServletRequest request , QueryVo queryVo){
        List<TaskModel> list = processService.getDeal(queryVo);
        return ResultJson.usePageInfo(new PageInfo<TaskModel>(list));
    }

    /**
     * 获取 流程办理历史
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getHistory", method = RequestMethod.POST)
    public Object getHistory(HttpServletRequest request){
        String instanceId = request.getParameter("instanceId");
        List<InstanceHistory> list = processService.getHistory(instanceId);
        return ResultJson.usePageInfo(new PageInfo<>(list));
    }
    
     /**
     * 完成任务页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/toExamine")
    public String toExamine(Model model, HttpServletRequest request) {
        String taskId = request.getParameter("taskId");
        String approverId =  request.getParameter("approverId");
        String executorName = request.getParameter("executorName");
        if(approverId!=null) model.addAttribute("approverId",approverId);
        if( executorName!= null  ) model.addAttribute("executorName", executorName);
        model.addAttribute("beforTaskModel", JSONObject.fromObject(processService.getBeforTaskByTaskId(taskId)));
        model.addAttribute("taskModel", JSONObject.fromObject(processService.getTaskByTaskId(taskId)));
        return "flowpages/taskExamine";
    }
    /**
     * 所有流程实例
     * @param request
     * @return
     */
    @RequestMapping("/allProcessList")
    public String allProcess(HttpServletRequest request){
        return "flowpages/taskAllProcessList";
    }
    
    /**办理任务
     * @param completeTaskRequest
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/completeTask")
    public Object completeTask(CompleteTaskRequest completeTaskRequest,
                               HttpServletRequest request) {
        if (completeTaskRequest.getTaskId() == null)
            return AjaxResult.Error();
        try {       	
        	completeTaskRequest.setTaskType(request.getParameter("taskType"));
        	String approverId = request.getParameter("approverId");
        //	String executorName = request.getParameter("executorName");
            boolean result = processService.useCompleteTask(completeTaskRequest , completeTaskRequest.getStartUserId() ,approverId  );
            if (!result) {
                return AjaxResult.Error("任务已被其他成员完成");
            }
        } catch (Exception ce) {
            ce.printStackTrace();
            return AjaxResult.Error(ce.getMessage());
        }
        return AjaxResult.Success();
    }

    /**
     *  终止进行中的流程实例
     * @param indtsnceId
     * @param taskName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelTask")
    public Object cancelTask(String indtsnceId,String taskName){
        try {
           // CancelTask result = flowTraceService.useCancelTask(indtsnceId,taskName);
        	CancelTask result = processService.revokeInstance(indtsnceId,taskName);
            if(CancelTask.SUCCESS.equals(result))
                return AjaxResult.Success("成功");
            else if(CancelTask.PROCESS_END.equals(result))
                return AjaxResult.Error("流程已终止");
            else if (CancelTask.TASK_BE_EXE.equals(result))
                return AjaxResult.Error("任务已被执行");
            else if (CancelTask.TASK_SUSPEND.equals(result))
                return AjaxResult.Error("流程被挂起");
            else if (CancelTask.NO_TASK.equals(result))
                return AjaxResult.Error("异常-没有任务信息");
            return AjaxResult.Error("异常");
        } catch (Exception e) {
            return AjaxResult.Error(e.getMessage());
        }
    }



}